package com.yan.test.work.testpaging3.net.response;

import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.yan.test.work.testpaging3.net.JsonContervUtil;
import com.yan.test.work.testpaging3.net.L;
import com.yan.test.work.testpaging3.net.ThreadUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;

/**
 * http响应处理（简化版）
 *
 * @Author YWY
 * @Time 2017/12/22
 */

public abstract class ResponseHandlerList<T> implements Callback {
    int stateCode;

    public int getStateCode() {
        return stateCode;
    }

    /**
     * 请求成功时回调
     *
     * @param responseModel  响应数据
     * @param dataJSONObject 响应data数据
     */
    public abstract void onSuccess(ResponseModelList<T> responseModel, JSONObject dataJSONObject);

    public void onSuccessGoMain(final ResponseModelList<T> responseModel, final JSONObject dataJSONObject) {
        ThreadUtil.runOnMainThread(() -> onSuccess(responseModel, dataJSONObject));
    }

    /**
     * 网络访问结束回调
     */
    public void onFinish() {

    }

    public void onFinishGoMain() {
        ThreadUtil.runOnMainThread(() -> onFinish());
    }

    /**
     * 请求失败时回调
     *
     * @param responseModel 响应数据
     */
    public abstract void onFailure(ResponseModelList<T> responseModel);

    public void onFailureGoMain(final ResponseModelList<T> responseModel) {
        ThreadUtil.runOnMainThread(() -> onFailure(responseModel));
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        String requsetUrl = call.request().url().toString();
        int index = requsetUrl.indexOf("?");
        if(index == -1) index = requsetUrl.length();
        String newUrl = requsetUrl.substring(0, index);

        if(call.isCanceled()) {
            onFinishGoMain();
        }else{
            loge("请求发送失败：", e);
            ResponseModelList<T> responseModel = new ResponseModelList<T>();
            responseModel.took = -1;
            if(e instanceof UnknownHostException){
                responseModel.total = "Por favor, compruebe si su red está disponible";
            } else if(e instanceof SocketTimeoutException){
                responseModel.total = "Retraso de red";
            } else {
                responseModel.total = "Por favor, compruebe si su red está disponible";
            }
            onFailureGoMain(responseModel);
            onFinishGoMain();
        }

    }

    @Override
    public void onResponse(final Call call, final Response response){
        String requsetUrl = call.request().url().toString();
        int index = requsetUrl.indexOf("?");
        if(index == -1) index = requsetUrl.length();
        String newUrl = requsetUrl.substring(0, index);
        try {
            if (response.isSuccessful()) {
                onSuccess(call, response);
            } else {
                onFailure(call, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 打印请求信息 */
    private void printResponse(int statusCode, Call call, Headers headers, String responseString, Throwable throwable) {
        if (throwable == null) {
            log("------http请求成功------");
        } else {
            log("------http请求失败------");
            log("异常描述：" + throwable.getMessage());
        }
        String requestURI = call.request().url().toString();
        if (requestURI != null) {
            log("请求地址：" + requestURI.toString());
        }
        log("响应状态码：" + statusCode);
        StringBuffer headerSb = new StringBuffer();
        if (headers != null) {
            for (String key : headers.names()) {
                String headerStr = headers.get(key);
                headerSb.append(key).append("=").append(headerStr).append(";");

            }
        }
        log("响应头：" + headerSb);
        log("响应数据：" + responseString);
    }


    public void onSuccess(Call call, Response response) throws IOException {
        Headers headers = response.headers();
        String responseString = response.body().string();
        int statusCode = response.code();
        stateCode = statusCode;
        printResponse(statusCode, call, headers, responseString, null);
        if (TextUtils.isEmpty(responseString)) {
            ResponseModelList<T> responseModel = new ResponseModelList<T>();
            responseModel.took = -1;
            responseModel.total = "SYSTEM_ERROR";
            onFailureGoMain(responseModel);
            onFinishGoMain();
            return;
        }

        ResponseModelList<T> responseModel = null;
        try {
//            responseModel = JSON.parseObject(responseString, ResponseModelList.class);
            Type type = new TypeToken<ResponseModelList<T>>(){}.getType();
            responseModel = JsonContervUtil.jsonToObject(responseString, type);
        } catch (Exception e) {
            e.printStackTrace();

        }
        if (responseModel == null) {
            responseModel = new ResponseModelList<T>();
            responseModel.took = -1;
            responseModel.total = "SYSTEM_ERROR";
            onFailureGoMain(responseModel);
            onFinishGoMain();
            return;
        }
        boolean success = responseModel.took > 0;
        // 业务执行成功时
        if (success) {
            Type superclass = getClass().getGenericSuperclass();
            if (superclass instanceof ParameterizedType) {
                ParameterizedType parameterized = (ParameterizedType) superclass;
                Type type = parameterized.getActualTypeArguments()[0];
                if (responseModel.articles != null) {
                    List<T> result = null;
                    try {
                        String dataStr = JsonContervUtil.objectToStr(responseModel.articles);
                        result = JsonContervUtil.jsonToList(dataStr , (Class<T>) type);
//                        result = JSON.parseArray(JSON.toJSONString(responseModel.datas), (Class<T>) type);
                        responseModel.articles = result;
                    } catch (Exception e) {
                        e.printStackTrace();
                        responseModel.articles = null;
                    }
                }
            }

            try {
                onSuccessGoMain(responseModel, new JSONObject(responseString));
                onFinishGoMain();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        } else {

//            if (responseModel == null) {
//                responseModel = new ResponseModelList<T>();
//                responseModel.resp_code = -1;
//                responseModel.resp_msg = "SYSTEM_ERROR";
//            }
//            // 业务执行失败，返回状态描述信息
//            onFailureGoMain(responseModel);
//            onFinishGoMain();
//            //Token 过期
//            if(responseModel.resp_code == -1001){
//                EventBus.getDefault().post(new BaseMsg("RELOGIN",""));
//            }
//            return;
        }
    }


    public void onFailure(Call call, Response response) throws IOException {
        // http请求失败，默认处理
        int statusCode = response.code();
        stateCode = statusCode;
        printResponse(statusCode, call, response.headers(), response.body().string(), new Exception(response.body().toString()));

        ResponseModelList<T> responseModel = new ResponseModelList<T>();
        responseModel.took = -1;
        responseModel.total = "SYSTEM_ERROR";
        onFailureGoMain(responseModel);
        onFinishGoMain();
    }




    private void log(String msg) {
        L.d(ResponseHandlerBean.class, msg);
    }

    private void loge(String msg, Exception e) {
        L.e(ResponseHandlerList.class, msg, e);
    }

//    private void show(final String msg) {
//        ThreadUtil.runOnMainThread(new Runnable() {
//            @Override
//            public void run() {
//                com.bbrightway.library.util.T.showMsgS(IWMSApp.getAppContext(), msg);
//            }
//        });
//    }
//
//    private void logout() {
//        show(ResponseStatus.PERMISSION_DENIED.getMsg());
//        CookieUtils.clear();
//        ActivityManager.getInstance().finishAllActivity();
//        Intent intent = new Intent();
//        intent.setAction("com.bbrightway.iwms.pcitc.app.login");
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        try {
//            IWMSApp.getAppContext().startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//            L.e("ResponseHandler", "exit");
//        }
//
//    }


}
